package logic

import (
	"context"
	"errors"
	"strconv"
	"video-hubs/model/cache"
	"video-hubs/model/mysql"

	"video-hubs/videorpc/internal/svc"
	"video-hubs/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if in.Type == 1 || in.Type == 2 {
		if in.Type == 1 {
			if err := user.FindUser(mysql.DB, in.Username); err != nil {
				return nil, errors.New("用户不存在")
			}
			if in.Password != user.Password {
				return nil, errors.New("密码错误")
			}
		}
		if in.Type == 2 {
			if err := user.FindUser(mysql.DB, in.Username); err != nil {
				return nil, errors.New("用户不存在")
			}

			result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Username).Result()
			if result == "" {
				return nil, errors.New("请先获取验证码")
			}

			if result != in.SendSms {
				return nil, errors.New("验证码错误")
			}
		}
	} else {
		return nil, errors.New("请输入正确的登陆方式")
	}

	return &videorpc.LoginResponse{
		Token: strconv.Itoa(int(user.ID)),
	}, nil
}
